import Deep from "./deep";

/*
 * @Descripttion: 
 * @version: 
 * @Author: Lee
 * @Date: 2020-05-26 10:56:34
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2020-05-27 14:51:30
 */
var $uid = 0;
export default class Watcher {
    constructor(exp, scope, cb) {
        this.exp = exp;
        this.scope = scope;
        this.cb = cb;
        this.uid = $uid++;
        this.update();

    }

    /**
     * @name: 计算表达式
     * @test: test font
     * @msg: 
     * @param {type} 
     * @return: 
     */
    get() {
        Deep.target = this;
        let newValue = Watcher.computeExpression(this.exp, this.scope);
        Deep.target = null;
        return newValue;

    }

    /**
     * @name: 完成回调函数的调用
     * @test: test font
     * @msg: 
     * @param {type} 
     * @return: 
     */
    update() {
        let newValue = this.get();
        this.cb && this.cb(newValue);
    }

    /**
     * @name: 静态计算表达式
     * @test: test font
     * @msg: 
     * @param {type} 
     * @return: 
     */
    static computeExpression(exp, scope) {
        // 创建函数
        // 把scope当作作用域
        // 函数内部使用with来指定作用域
        // 执行函数，得到表达式的值
        let fn = new Function("scope", "with(scope){return " + exp + "}");
        return fn(scope);
    }
}